package com.uduemc.jcms.backend.controller;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.uduemc.jcms.common.utils.JsonResult;
import com.uduemc.jcms.common.utils.PageDataUtil.PageData;
import com.uduemc.jcms.entity.Categories;
import com.uduemc.jcms.service.ICategoriesService;
import com.uduemc.jcms.vo.CategorySave;

@Controller
@RequestMapping("/backend/category")
public class BCategoryController {

	@Autowired
	ICategoriesService categoriesServiceImpl;

	@GetMapping(value = "/infos.html")
	@ResponseBody
	public JsonResult infos(@RequestParam("type_table") String typeTable, @RequestParam("type") int type,
			@RequestParam(value = "parent_id", defaultValue = "-1") int parentId, @RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "path", defaultValue = "") String path, @RequestParam(value = "page", defaultValue = "1") int page,
			@RequestParam(value = "rows", defaultValue = "10") int rows) throws IOException {
		PageData<Categories> selectPageInfos = categoriesServiceImpl.selectPageInfos(typeTable, type, parentId, name, path, page, rows);
		return JsonResult.ok(selectPageInfos);
	}

	@GetMapping(value = "/dropdown-infos.html")
	@ResponseBody
	public JsonResult dropdownInfos(@RequestParam("type_table") String typeTable, @RequestParam("type") int type,
			@RequestParam(value = "deep", defaultValue = "2") int deep) throws IOException {
		PageData<Categories> selectPageInfos = categoriesServiceImpl.selectDeepInfos(typeTable, type, deep);
		return JsonResult.ok(selectPageInfos);
	}

	@PostMapping(value = "/save.html")
	@ResponseBody
	public JsonResult save(@RequestBody @Validated CategorySave categorySave, BindingResult bindingResult) {
		JsonResult messageError = JsonResult.messageError(bindingResult);
		if (messageError != null) {
			return messageError;
		}
		if (!categoriesServiceImpl.save(categorySave)) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess(1);
	}
}
